package com.jj.service.player;

import com.google.protobuf.GeneratedMessageV3;
import com.jj.battle.protocol.ProtocolId;
import com.jj.core.client.Client;
import com.jj.core.client.impl.ClientManagerImpl;
import com.jj.message.PBMessageFactory;
import com.jj.message.ProtoFormat;
import com.jj.message.battle.UserMessage;
import com.jj.service.entity.EntityImpl;
import com.jj.service.room.Room;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyrights: QidianGroup@JJ
 *
 * @author: LuHan
 * @date: 2018/1/15, 16:01
 */
@Data
public class PlayerImpl extends EntityImpl implements Player{
    private static Logger logger = LoggerFactory.getLogger(PlayerImpl.class);

    private PBMessageFactory pbMessageFactory;
    private ClientManagerImpl clientManager;
    private int characterId;
    private volatile boolean hasSyn = false;

    private Room room;

    public PlayerImpl(ClientManagerImpl clientManager, PBMessageFactory pbMessageFactory){
        this.clientManager = clientManager;
        this.pbMessageFactory = pbMessageFactory;
    }

    @Override
    public void send(UserMessage message) {
        logger.debug("prepare to send {} to {}", message, getUserId());
        Client client = clientManager.get(getUserId());
        if(client != null){
            client.sendKcp(message);
            //client.sendTcp(message);
        }else{
            logger.error("client not found for {}, ignore msg:{}", getUserId(), message);
        }
    }

    @Override
    public void send(GeneratedMessageV3 pbMessage) {
        //logger.debug("prepare to send msg [{}] to user:{}", pbMessage, getUserId());
        UserMessage userMessage = new UserMessage();
        Short msgIdx = pbMessageFactory.getMsgIdx(pbMessage);
        if(msgIdx == null){
            logger.error("can not get msgID for {}", pbMessage);
            return;
        }else if (!hasSyn && msgIdx == ProtocolId.ProtoId.MSG_SYN_STATE_REQ.getNumber()){
            logger.debug("hasSyn:{}, ignore {}", hasSyn, pbMessage);
        }else {
            userMessage.setMsgID(msgIdx);
            userMessage.setProtocolFormat(ProtoFormat.ProtoBuf);
            userMessage.setPayload(pbMessageFactory.serialize(pbMessage));
            send(userMessage);
            //logger.debug("player {} send [{}]", getUserId(), pbMessage);
        }
    }

    @Override
    public int getCharacterId() {
        return characterId;
    }

    @Override
    public void setCharacterId(int characterId) {
        this.characterId = characterId;
    }

    public Room getRoom() {
        return room;
    }

    public void setRoom(Room room) {
        this.room = room;
    }
}
